package com.thenie.service.impl;

import com.thenie.dao.OrderDao;
import com.thenie.dao.OrderItemDao;
import com.thenie.dao.impl.OrderDaoImpl;
import com.thenie.dao.impl.OrderItemDaoImpl;
import com.thenie.pojo.*;
import com.thenie.service.OrderService;

import java.util.Date;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
    @Override
    public String createOrder(Cart cart, Integer userId) {
        OrderDao orderDao =new OrderDaoImpl();
        OrderItemDao orderItemDao =new OrderItemDaoImpl();
        BookServiceImpl bookService = new BookServiceImpl();
        //获取当前订单号（时间戳+用户id）
        String orderId= String.valueOf(System.currentTimeMillis()+userId);
        //创建Order类
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        //添加订单
        orderDao.createOrder(order);
        //添加订单详情
        for (Map.Entry<Integer, CartItem> entry : cart.getMap().entrySet()) {
            CartItem value = entry.getValue();
            orderItemDao.createOrderItem(new OrderItem(null, value.getId(), value.getName(), value.getCount(), value.getPrice(), value.getTotalPrice(), orderId));

            //改变这本书籍的销量和库存
            int id = value.getId();
            int count = value.getCount();
            Book book = bookService.queryBook(id);

            book.setSales(book.getSales()+count);
            book.setStock(book.getStock()-count);
            bookService.updateBook(book);
        }

        return orderId;
    }
}
